<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Model\Admin\Admin;
use App\Model\Business;
use App\Model\Device;
use App\Model\DistributorDevice;
use App\Model\Order;
use App\Services\SmsService;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use RedisException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use App\Controller\AbstractController;
use App\Model\Distributors;
use App\Services\AdapayService;

class DistributorsController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected Admin $admin;
    #[Inject]
    protected Distributors $distributors;


    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**经销商列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getList(RequestInterface $request): ResponseInterface
    {
        $page = $request->inputs([
            'page',
            'limit',
            'keyword',
            'parent_id',
            'is_active',
            'level'
        ]);

        $page['info'] = $this->admin->getInfo($request);
        $query = $this->distributors->where(function ($query) use ($page) {
            if (!empty($page['keyword'])) {
                $query->where('name', 'like', "%{$page['keyword']}%")
                    ->orWhere('mobile', 'like', "%{$page['keyword']}%");
            }
            if ($page['is_active'] !== '') {
                $query->where('is_active', $page['is_active']);
            }
            if ($page['info']['type'] == Admin::TYPE_USER) {
                $query->where('parent_id', $page['info']['distributor_id']);
            } else {
                if ($page['parent_id']) {
                    $query->where('parent_id', $page['parent_id']);
                }
                if ($page['level'] > 0) {
                    $query->where('level', $page['level']);
                }
            }
        });
        $data['total'] = $query->count();
        $data['list'] = $query->withCount([
            'deviceProfit as distributor_profit' => function($q) {
                $q->select(Db::raw('SUM(profit)'));
            },
            'device as device_count',
            'order as order_count'
        ])
//            ->select([
//                'id', 'avatar', 'name', 'owner_name', 'mobile', 'remark',
//                'rate', 'is_active', 'settlement_type',
//                'parent_id', 'level', 'balance', 'service_image',
//                'created_at', 'customer_service_phone'
//            ])
            ->orderBy('id', 'desc')
                ->offset(($page['page'] - 1) * $page['limit'])
                ->limit($page['limit'])
            ->get()
            ->map(function ($item) {
                // 确保统计字段存在（Hyperf特殊处理）
                return array_merge($item->toArray(), [
                    'device_count' => $item->device_count ?? 0,
                    'order_count' => $item->order_count ?? 0,
                    'distributor_profit' => $item->distributor_profit ?? 0
                ]);
            });
        return $this->success($data);
    }

    /** 提现记录列表
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function outCash(RequestInterface $request): ResponseInterface
    {
        $info = $this->admin->getInfo($request);
        $page = $request->inputs([
            'page',
            'limit',
            'cash_type',
            'distributor_id',
            'time',
            'status',
            'is_return'
        ]);

        // 构建查询条件
        $queryConditions = function ($query) use ($page, $info) {
            // 经销商ID筛选
            if (!empty($page['distributor_id'])) {
                $query->where('c.distributor_id', $page['distributor_id']);
            } else {
                if (isset($info['distributor_id']) && $info['distributor_id']) {
                    $query->where('c.distributor_id', $info['distributor_id']);
                } else {
                    $query->where('c.distributor_id', '>', 0);
                }
            }

            // 提现类型筛选
            if ($page['cash_type'] !== '') {
                $query->where('c.cash_type', $page['cash_type']);
            }

            // 状态筛选
            if ($page['status'] !== '' && $page['status'] !== null) {
                $query->where('c.status', $page['status']);
            }

            // 是否退回筛选
            if ($page['is_return'] !== '' && $page['is_return'] !== null) {
                $query->where('c.is_return', $page['is_return']);
            }

            // 时间范围筛选
            if (!empty($page['time']) && is_array($page['time'])) {
                $query->where('c.created_at', '>=', $page['time'][0])
                    ->where('c.created_at', '<=', $page['time'][1]);
            }
        };

        // 查询列表数据
        $data['list'] = Db::table('cash_log as c')
            ->leftJoin('distributors as d', 'c.distributor_id', '=', 'd.id')
            ->where($queryConditions)
            ->orderBy('c.id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->select('c.*', 'd.name')
            ->get();

        // 查询总数
        $data['total'] = Db::table('cash_log as c')
            ->leftJoin('distributors as d', 'c.distributor_id', '=', 'd.id')
            ->where($queryConditions)
            ->count();

        return $this->success($data);
    }


    /**
     * 所有经销商列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getAll(RequestInterface $request):ResponseInterface
    {
        $page = $request->inputs(['page','limit']);
        $data['list'] = $this->distributors
            ->orderBy('id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->get();
        $data['total']= $this->distributors->count();
        return $this->success($data);
    }

    /**获取联级菜单经销商
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function all(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        $info =  $this->admin->getInfo($request);
        if($info['type'] != Admin::TYPE_USER){
            $list = $this->distributors->where('level',  Distributors::LEVEL_1)->orderBy('id', 'desc')
                ->get(['id','name','level'])->toArray();
        }else{
            $list = $this->distributors->where('level',  Distributors::LEVEL_1)
                ->where('id',$info['distributor_id'])
                ->orderBy('id', 'desc')
                ->get(['id','name','level'])->toArray();
        }
        if($list){
            foreach($list as $k => $v){
                $list[$k]['children'] = $this->distributors
                    ->where('level',  Distributors::LEVEL_2)
                    ->where('parent_id',$v['id'])
                    ->orderBy('id', 'desc')
                    ->get(['id','name','level'])
                    ->toArray();
            }
        }
        return $this->success($list);
    }

    /**修改状态
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function changeStatus(RequestInterface $request):ResponseInterface
    {
        $status = $request->input('is_active',0,'int');
        $id = $request->input('id',0,'int');
        if (!$id) {
           return $this->error(code:1001,msg:'缺失参数id');
        }
        $this->distributors->where('id',$id)->update(['is_active'=>$status]);
        return $this->success(msg:'修改成功');
    }

    public function changePass(RequestInterface $request):ResponseInterface
    {
        $password = $request->input('password',0,'int');
        $id = $request->input('id',0,'int');
        if (!$id) {
            return $this->error(code:1001,msg:'缺失参数id');
        }
        if(!$password){
            return $this->error(code:1001,msg:'请输入密码');
        }
        $password = password_hash($password, PASSWORD_DEFAULT);
        $this->distributors->where('id',$id)->update(['password'=>$password]);
        return $this->success(msg:'修改成功');
    }


    private function updateDistributor(int $id, array $data): void {
        if (isset($data['parent_id'])) {
            $parentLevel = $this->distributors->where('id', $data['parent_id'])->value('level');
            if ($parentLevel >= Distributors::LEVEL_MAX) {
                throw new \RuntimeException('经销商层级超过限制');
            }
            $data['level'] = $parentLevel + 1;
        }else{
            if($data['parent_id'] == 0){
                $data['level'] = Distributors::LEVEL_1;
            }
        }
        $this->distributors->where('id', $id)->update($data);
    }

    private function createDistributor(array $data): void
    {
        if (isset($data['parent_id'])) {
            $parentLevel = $this->distributors->where('id', $data['parent_id'])->value('level');
            if ($parentLevel >= Distributors::LEVEL_MAX) {
                throw new \RuntimeException('经销商层级超过限制');
            }
            $data['level'] = $parentLevel + 1;
        }
        Distributors::create($data);
    }
        /**创建经销商
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function create(RequestInterface $request): ResponseInterface {
        $data = $request->post();
        $info = $this->admin->getInfo($request);
        // 基础验证
        if (!isset($data['parent_id']) || !$data['parent_id']) {
            $data['parent_id'] = 0;
            $data['level'] = Distributors::LEVEL_1;
        }
        if (!$data['mobile']) {
            return $this->error(code: 1001, msg: '手机号不能为空');
        }
        if(isset($data['balance']) || !$data['balance']){
            $data['balance'] = 0;
        }
        if (!$data['name']) {
            return $this->error(code: 1001, msg: '名称不能为空');
        }
        if($info['type'] != Admin::TYPE_ADMIN){
            if(isset($data['balance'])){
                unset($data['balance']);
            }
            $distributor = $this->distributors->where('mobile', $info['mobile'])->first();
            if(!$distributor || $distributor['level'] != Distributors::LEVEL_1){
                return $this->error(code: 1001, msg: '不可创建子经销商');
            }else{
                $data['parent_id'] = $distributor['id'];
            }
        }
        if ($data['rate'] > 100) {
            return $this->error(code: 1001, msg: '经销商分润不可超过100');
        }
        if(!isset($data['id']) || !$data['id']){
            $data['password'] = empty($data['password'])
                ? $data['mobile']
                : $data['password'];
            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        }
        // 密码处理
        try {
            if (isset($data['id']) && $data['id']) {
                $id = (int)$data['id'];
                unset($data['id']);
                $this->updateDistributor($id, $data);
            } else {
                $this->createDistributor($data);
            }
            return $this->success();
        } catch (\Exception $e) {
            return $this->error(500, $e->getMessage());
        }
    }


    /**获取经销商绑卡信息
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function getBankInfo(RequestInterface $request):ResponseInterface{
        $id = $request->input('distributor_id',0);
        $distributor = $this->distributors->where('id',$id)
            ->first(['balance','frozen_balance','total_profit',
                'withdraw_account_type','withdraw_auto_type','withdraw_account_bank_card_username',
                'withdraw_account_bank_card_no','withdraw_account_bank_code',
                'withdraw_account_bank_name','cert_id','settle_account_id','settlement_type']);
        $distributor['bus_account'] = Business::where('distributor_id',$id)
            ->first();
        if(!$distributor){
            return $this->error(1001,'无经销商信息');
        }
        if($distributor['withdraw_account_bank_card_no']){
            $distributor['withdraw_account_bank_card_no'] = $this->normal->maskBankCard($distributor['withdraw_account_bank_card_no']);
        }
        if($distributor['cert_id']){
            $distributor['cert_id'] = $this->normal->maskIDNumber($distributor['cert_id']);
        }
        if($distributor['bus_account'] && $distributor['bus_account']['card_no']){
            $distributor['bus_account']['card_no'] = $this->normal->maskBankCard($distributor['bus_account']['card_no']);
        }
        return $this->success($distributor);
    }

}
